<?php
/**
 * github webhook钩子，push自动升级
 * User: wuxin
 * Date: 2019/7/7
 * Time: 10:31
 */

define('ROOT', dirname(dirname(dirname(__FILE__))));
define('LOG_FILE', '/home/wwwlogs/pro_webhook.log');
define('EVENT', isset($_SERVER['HTTP_X_GITHUB_EVENT']) ? $_SERVER['HTTP_X_GITHUB_EVENT'] : null);
define('SIGNATURE', isset($_SERVER['HTTP_X_HUB_SIGNATURE']) ? $_SERVER['HTTP_X_HUB_SIGNATURE'] : null);
define('SECRET', 'sports'); //webhook的秘钥

$playload = file_get_contents('php://input');

if (!EVENT || !SIGNATURE || !$playload) {
    exit('request error！');
}

list($algo, $hash) = explode('=', SIGNATURE, 2);

// 判断签名是否匹配
if ($hash !== hash_hmac($algo, $playload, SECRET)) {
    exit('签名错误！');
}

$playload = $playload ? json_decode($playload, true) : null;

wlog('事件数据[header]：'.PHP_EOL.var_export($_SERVER, true));
wlog('事件数据[playload]：'.PHP_EOL.var_export($playload, true));

//只有push的时候，更新代码
$func = 'event_'.strtolower(EVENT);
if (function_exists($func)) {
    $res = call_user_func($func, $playload) ? 'success' : 'error';
    echo "$res event [".EVENT."]";
} else {
    echo "failed event [".EVENT."]";
}


function wlog($data)
{
    $date = date('Y-m-d H:i:s');
    file_put_contents(LOG_FILE, "[{$date}]".(!is_string($data) ? var_export($data, true) : $data).PHP_EOL, FILE_APPEND);
}

/**
 * 升级
 * @param $playload
 * @return bool
 */
function event_push($playload)
{
    $cmd[] = "cd ".ROOT." && sudo git pull origin master 2>&1"; //配置缓存
    $cmd[] = "cd ".ROOT." && composer update 2>&1"; //配置缓存
    $cmd[] = "cd ".ROOT." && composer dumpautoload -o 2>&1";  //自动加载优化
    foreach ($cmd as $command) {
        $exitCode = 0;
        $output = null;
        @exec($command, $output, $exitCode);
        $log = array('command' => $command." (exitCode:{$exitCode})", 'output' => $output ? implode("\n", $output) : '');
        wlog($log);
    }
    $commit = $playload['head_commit'];
    $message = "最新版本：ID=>{$commit['id']};Author=>{$commit['author']}({$commit['email']});Message=>{$commit['message']}";
    wlog($message);
    wlog($commit);
    return true;
}

/**
 * ping 测试
 * @param $playload
 */
function event_ping($playload)
{
    var_export($playload);exit;
}
